/**
 * 
 */
package cn.boodqian.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.*;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.http.*;

import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

/**
 * @author Bood
 *
 */
public class ServerMessageTask extends AsyncTask<String, HashMap<String,String>, Long> {

	private Handler handler;
	private String agent;
	
	@Override
	protected Long doInBackground(String... urls) {
			if(urls.length < 1) return null;
	
			BasicHttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(httpParameters, 15000); // 15s timeout
			DefaultHttpClient client = new DefaultHttpClient(httpParameters);
			HttpGet get = new HttpGet(urls[0]);
			//get.setHeader("User-Agent", agent);
			HttpResponse responseGet = null;
			try {
				Log.i("Pre-request of server message:"+urls[0]);
				responseGet = client.execute(get);
				Log.i("Post-request of server message");

				HttpEntity resEntityGet = null;
				resEntityGet = responseGet.getEntity();
				if (resEntityGet != null) {
					String s = EntityUtils.toString(resEntityGet, HTTP.UTF_8);
					//Log.i(String.format("server message=%s", s));
					HashMap<String,String> map = new HashMap<String,String>();
					
					// Message format: key:{message body}
					Pattern p = Pattern.compile("(?ms)^([a-z0-9-]+?):\\{(.+?)\\}$");
					Matcher m = p.matcher(s);
					while (m.find()) {
						Log.i(String.format("%s:%s", m.group(1),m.group(2)));
						map.put(m.group(1), m.group(2));
					}
					publishProgress(map);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		return null;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	 */
	@Override
	protected void onProgressUpdate(HashMap<String, String>... values) {
		if(values == null || values.length==0) return;
		
		// Send message to listening activity through handler
		Message msg = new Message();
		msg.obj = values[0];
		handler.sendMessage(msg);
	}

	public ServerMessageTask(Handler handler, String agent) {
		super();
		this.handler = handler;
		this.agent = agent;
	}

}
